# -*- coding: utf-8 -*-
import sys
import os
import django
sys.path.append("..")
sys.path.append("../utils")
os.environ.update({"DJANGO_SETTINGS_MODULE": "server.settings1"})
django.setup()

import os
import shutil
import uuid
import oss2
import requests
import tempfile
import pdb
from user.models import *


class Store :
    def __init__(self, type="NORMAL"):
        access_key_id =  "LTAI4FgnXrb2X83KkQqYjMfK"
        access_key_secret = "i3P8vdE2gipEmsrpcXgit2c0cyV5Qz"
        bucket_name = "record--file"
        endpoint_out = "oss-cn-beijing.aliyuncs.com"
        self.bucket_name = bucket_name
        self.endpoint = endpoint_out
        self.bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), self.endpoint, self.bucket_name)
        self.name_prefix_len = 37
        self.endpoint_out = endpoint_out

    def upload_and_return_name(self, file_name):
        with open(oss2.to_unicode(file_name), 'rb') as f:
            name = str(uuid.uuid1()) + "_" + os.path.basename(f.name)
            headers = {"Content-Disposition": os.path.basename(f.name)}
            self.bucket.put_object(name, f)
            return name
    # 下载
    def return_download_file_url(self, file_name):
        # 验证文件是否存在
        exist = self.bucket.object_exists(file_name)
        # 返回值为true表示文件存在，false表示文件不存在。
        if exist:
            print('object exist')
            # 验证存在然后在下载文件
            return self.bucket.sign_url('GET', file_name, 60)
        else:
            print('object not eixst')

    # 删除
    def delete_file(self, file_name):
        # 验证文件是否存在
        exist = self.bucket.object_exists(file_name)
        # 返回值为true表示文件存在，false表示文件不存在。
        if exist:
            print('object exist')
            # 验证存在然后在删除文件
            self.bucket.delete_object(file_name)
        else:
            print('object not eixst')

    # 上传文件
    def upload_and_return_id(self, file_name, fileType=0,):
        ossname = self.upload_and_return_name(file_name)
        fileStore = FileStore.objects.create(
            ossname=ossname,
            fileType=fileType,
        )
        return fileStore.id

    # 上传文件
    def getUrl(self, fileStoreId):
        fileStore = FileStore.objects.get(pk=fileStoreId)
        return self.return_download_file_url(file_name=fileStore.ossname)
       
    # 设置文件权限
    def set_file_acl(self, file_name):
        """
        继承Bucket     oss2.OBJECT_ACL_DEFAULT
        私有           oss2.OBJECT_ACL_PRIVATE
        公共读         oss2.OBJECT_ACL_PUBLIC_READ
        公共读写       oss2.OBJECT_ACL_PUBLIC_READ_WRITE
        """
        # 验证文件是否存在
        exist = self.bucket.object_exists(file_name)
        # 返回值为true表示文件存在，false表示文件不存在。
        if exist:
            print('object exist')
            # 验证存在然后在设置文件权限
            self.bucket.put_object_acl(file_name, oss2.OBJECT_ACL_PRIVATE)
        else:
            print('object not eixst')

    # 获取文件权限
    def get_file_acl(self, file_name):
        # 验证文件是否存在
        exist = self.bucket.object_exists(file_name)
        # 返回值为true表示文件存在，false表示文件不存在。
        if exist:
            print('object exist')
            # 验证存在然后在获取文件权限
            return self.bucket.get_object_acl(file_name).acl
        else:
            print('object not eixst')

    # 列举文件
    def get_file_size(self, file_name):
        pass

    def get_file_info(self, file_name):
        # 验证文件是否存在
        exist = self.bucket.object_exists(file_name)
        # 返回值为true表示文件存在，false表示文件不存在。
        if exist:
            print('object exist')
            # 验证存在然后在获取文件信息
            # 获取文件的全部元信息
            objectmeta = self.bucket.head_object(file_name)
            print(objectmeta.headers['Content-Type'])
            print(objectmeta.headers['Last-Modified'])
            print(objectmeta.headers['x-oss-object-type'])
        else:
            print('object not eixst')


if __name__ == "__main__" :
    
    # 生成一个待上传的临时文件
    os.system("echo hello!!! > 1.txt")
    # 默认存储
    storeTools = Store()
    user = UserInfo.objects.get(pk=1)
    storeTools.upload_and_return_id('1.txt', user)
    # pdb.set_trace()
    # 冷存储
    # mo2 = migi_oss(type="COLD")
    # 返回值：(oss上的文件名, 自己下载使用时的url，传给客户端或者浏览器时的url)
    # urls = storeTools.upload_and_return_name()
    # print(urls)
    # pdb.set_trace()
    # tmpUrl = mo1.return_download_file_url(urls)
    # set = mo1.set_file_acl(urls)
    # get = mo1.get_file_acl(urls)
    # info = mo1.get_file_info(urls)
    # pdb.set_trace()
    # dele = mo1.delete_file(urls)

